#!/bin/bash
########################################################################   
#    Dooplet is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Dooplet is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Dooplet.  If not, see <http://www.gnu.org/licenses/>.
#######################################################################
#    Authors: Karthikeyan Manivannan Carlos Báez
#
######################################################################

#script installs the dooplet as a cron job
#that contacts the dooplet server every minute  
#the dooplet server can be set in the dooplet.py file

#First point to prepare a package
#set -e


temp_crontab_file="/usr/dooplet/dooplet.crontab"

#these rules report back and check for updates every minute
#note: cron output can be redirected to /dev/null if desired
report_back_crontab_rule="* * * * * /usr/dooplet/dooplet.py >> /tmp/dooplet_client.log"
getcpu_crontab_rule="0 12 1 * * /usr/dooplet/getcpu.sh >> /tmp/dooplet_client.log"
update_crontab_rule="* * * * * (sudo /usr/bin/apt-get -y install dooplet) >> /tmp/dooplet_client.log"

#check if dooplet directory exists
if [ ! -d "/usr/dooplet" ];
then
    echo "exiting: dooplet directory does not exist."
    exit -1;
fi

#check if python is installed
python_executable=`which python 2>/dev/null`
if [ "$python_executable" = "" ] ;
then
  echo "no python installation found on path.."
  exit 1;
fi

#TBD make sure cron job is started on laptop startup
#TBD cron error checking
#TBD check if dooplet already part of crontab

# create new crontab file with rule for dooplet
# append current crontab rules to new crontab file
# set crontab to use new crontab file
cd "/usr/dooplet"

confirm="n"

while [ "$confirm" != y ]
do
    # get the laptop id from the user
    echo -n "Please enter the laptop id: "
    read laptop_id
    echo -n "You entered $laptop_id , is that correct (y/n): "
    read confirm
done

echo "Saving labdoo id $laptop_id"
echo $laptop_id > laptop_id.txt
echo  "Configuring crontab for reports "
echo "$report_back_crontab_rule" > "$temp_crontab_file"
echo "Configuring crontab for rules "
echo "$getcpu_crontab_rule" >> "$temp_crontab_file"
echo  "Configuring crontab for updates "
echo "$update_crontab_rule" >> "$temp_crontab_file"
current_crontab=`crontab -l 2>/dev/null`
echo  "Adding current crontab.."
echo "$current_crontab" >> "$temp_crontab_file"

crontab "$temp_crontab_file" 2>/dev/null
rm "$temp_crontab_file"

echo "Configuring widget to check hardware"


